package com.supertange.miniapp.wepet.modules.wepet.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import com.supertange.miniapp.wepet.common.controller.BaseController;
import com.supertange.miniapp.wepet.common.utils.*;
import com.supertange.miniapp.wepet.common.vo.AjaxResult;
import com.supertange.miniapp.wepet.modules.wepet.entity.CommentsEntity;
import com.supertange.miniapp.wepet.modules.wepet.entity.Videos;
import com.supertange.miniapp.wepet.modules.wepet.enums.VideoStatusEnum;
import com.supertange.miniapp.wepet.modules.wepet.service.BgmService;
import com.supertange.miniapp.wepet.modules.wepet.service.UserService;
import com.supertange.miniapp.wepet.modules.wepet.service.VideoService;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

@RestController
@RequestMapping("/video")
@Api(value = "视频相关业务的接口", tags = {"视频相关业务的controller"})
public class VideoController extends BaseController {
    @Autowired
    BgmService bgmService;
    @Autowired
    VideoService videoService;
    @Autowired
    UserService userService;
    @Autowired
    WxMaService wxMaService;

    @ApiOperation(value = "上传视频", notes = "上传视频的接口")
    @PostMapping(value = "/upload", headers = "content-type=multipart/form-data")
    @Transactional(propagation = Propagation.REQUIRED)
    public AjaxResult upload(String userId,
                             String bgmId,
                             double videoSeconds,
                             int videoWidth,
                             int videoHeight,
                             String desc,
                             @ApiParam(value = "短视频", required = true)
                                     MultipartFile file) throws Exception {
        //判断传入的id是否为空
        if (StringUtils.isBlank(userId)) {
            return AjaxResult.errorMsg("用户id不能为空...");
        }
        Assert.isTrue(wxMaService.getSecCheckService().checkMessage(desc), "请正确发言");

        //获取视频名称
        String fileName = file.getOriginalFilename();
        //小程序临时文件名称
        String arrayFilenameItem[] = fileName.split("\\.");

        String fileNamePrefix = "";
        for (int i = 0; i < arrayFilenameItem.length - 1; i++) {
            fileNamePrefix += arrayFilenameItem[i];
        }

        //七牛云上传
        String videoPath = qnVideoUpload(file);
        String waterVideoPath=qnVideoAddWater(videoPath);

        //七牛云视频截取图片
        String coverPath = qnVideoPatchCover(videoPath);

        // 保存视频信息到数据库
        Videos video = new Videos();
        video.setAudioId(bgmId);
        video.setUserId(userId);
        video.setVideoSeconds((float) videoSeconds);
        video.setVideoHeight(videoHeight);
        video.setVideoWidth(videoWidth);
        video.setVideoDesc(desc);
        video.setVideoRealPath(videoPath);
        video.setVideoPath(waterVideoPath);
        video.setCoverPath(coverPath);
        video.setStatus(VideoStatusEnum.SUCCESS.value);
        String videoId = videoService.saveVideo(video);
        return AjaxResult.ok(videoId);
    }

    @PostMapping("/uploadCover")
    public AjaxResult uploadCover(@RequestParam MultipartFile file) throws Exception {
        String coverImg = qnImageUpload(file);
        return AjaxResult.ok(coverImg);
    }

    @PostMapping("/deleteVideo")
    @Transactional(propagation = Propagation.REQUIRED)
    public AjaxResult deleteVideo(@RequestParam String  videoId,
                                  @RequestParam String userId) {
        Videos videos=videoService.queryOneVideo(videoId);
        if (videos==null) Assert.isError("删除失败");
        if (!videos.getUserId().equals(userId)) Assert.isError("删除失败");
        String deleteFiles[] = new String[3];
        deleteFiles[0]=videos.getCoverPath();
        deleteFiles[1]=videos.getVideoPath();
        deleteFiles[2]=videos.getVideoRealPath();

        //删除多个数据
        qnDeleteFiles(deleteFiles);

        //删除视频及相关
        videoService.deleteVideo(videoId,userId);

        return AjaxResult.ok();
    }

    /**
     * 查看所有(时间排序)
     *
     * @param video
     * @param isSaveRecord
     * @param page
     * @param pageSize
     * @return
     */
    @PostMapping("/showAll")
    @ApiOperation(value = "显示所有")
    public AjaxResult showAll(@RequestBody Videos video,
                              Integer isSaveRecord,
                              Integer isShuffle,
                              Integer page,
                              Integer pageSize) {
        if (page == null) page = PAGE;
        if (pageSize == null) pageSize = PAGE_SIZE;
        PagedResult voList = videoService.getAllVideos(video, isSaveRecord, isShuffle, page, pageSize);
        return AjaxResult.ok(voList);
    }

    /**
     * @Description: 我关注的人发的视频
     */
    @PostMapping("/showMyFollow")
    public AjaxResult showMyFollow(String userId, Integer page) {

        if (StringUtils.isBlank(userId)) {
            return AjaxResult.ok();
        }

        if (page == null) {
            page = 1;
        }

        int pageSize = 6;

        PagedResult videosList = videoService.queryMyFollowVideos(userId, page, pageSize);

        return AjaxResult.ok(videosList);
    }

    /**
     * @Description: 我收藏(点赞)过的视频列表
     */
    @PostMapping("/showMyLike")
    public AjaxResult showMyLike(String userId, Integer page, Integer pageSize) {

        if (StringUtils.isBlank(userId)) {
            return AjaxResult.ok();
        }

        if (page == null) {
            page = 1;
        }

        if (pageSize == null) {
            pageSize = 6;
        }

        PagedResult videosList = videoService.queryMyLikeVideos(userId, page, pageSize);

        return AjaxResult.ok(videosList);
    }

    @PostMapping(value = "/hot")
    public AjaxResult hot() {
        return AjaxResult.ok(videoService.getHotwords());
    }

    @PostMapping(value = "/userLike")
    public AjaxResult userLike(String userId, String videoId, String videoCreaterId) {
        videoService.userLikeVideo(userId, videoId, videoCreaterId);
        return AjaxResult.ok();
    }

    @PostMapping(value = "/userUnLike")
    public AjaxResult userUnLike(String userId, String videoId, String videoCreaterId) {
        videoService.userUnLikeVideo(userId, videoId, videoCreaterId);
        return AjaxResult.ok();
    }

    @PostMapping("/saveComment")
    public AjaxResult saveComment(@RequestBody CommentsEntity comment,
                                  String fatherCommentId, String toUserId) {
        Assert.isTrue(wxMaService.getSecCheckService().checkMessage(comment.getComment()), "请正确发言");
        comment.setFatherCommentId(fatherCommentId);
        comment.setToUserId(toUserId);

        videoService.saveComment(comment);
        return AjaxResult.ok();
    }

    @PostMapping("/getVideoComments")
    public AjaxResult getVideoComments(String videoId, Integer page, Integer pageSize) {

        if (StringUtils.isBlank(videoId)) {
            return AjaxResult.ok();
        }

        // 分页查询视频列表，时间顺序倒序排序
        if (page == null) {
            page = 1;
        }

        if (pageSize == null) {
            pageSize = 10;
        }

        PagedResult list = videoService.getAllComments(videoId, page, pageSize);

        return AjaxResult.ok(list);
    }
}
